package org.adorsys.aderp.aderplogin.roles;


/**
 * This is used to match simple contextual role attributes. It doesn't
 * lookup permission or subprofiles held by a permission profile.
 * 
 * The permission bring check 
 * 
 * @author francis
 *
 */
public class SimpleContextualAttrEval implements ContextualAttrEval {

	private ContextualRole requiredRole;
	
	public SimpleContextualAttrEval(String role) {
		requiredRole = new ContextualRole(role);
	}

	/**
	 * A contextual role match another contextual role only if the permission
	 * profiles matches and the context matches.
	 * 
	 * If the required role has no context, only the permission profile if
	 * matches.
	 * 
	 * We used the wildcard based hierarchy of the java security permission
	 * match each part.
	 */
	@Override
	public int match(String role) {
		ContextualRole providedRole = new ContextualRole(role);

		// match permission profile
		boolean implies = requiredRole.getPermProf().implies(providedRole.getPermProf());
		if(!implies) return ContextualRoleVoter.ACCESS_DENIED;
		
		// grant if no context
		if(requiredRole.getContext()==null) return ContextualRoleVoter.ACCESS_GRANTED;
		
		// deny it provided has no context and required has a context
		if(providedRole.getContext()==null) return ContextualRoleVoter.ACCESS_DENIED;
		
		// match both contexts
		implies = requiredRole.getContext().implies(providedRole.getContext());
		if(!implies) return ContextualRoleVoter.ACCESS_DENIED;
		
		// grant.
		return ContextualRoleVoter.ACCESS_GRANTED;
	}
	

}
